import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Editor } from 'react-draft-wysiwyg';
import { EditorState, convertToRaw, convertFromHTML, ContentState } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';

import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Checkbox,
  Radio,
  Badge,
  Divider,
} from 'antd';
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const confirm = Modal.confirm;
import DescriptionList from 'components/DescriptionList';
const { Description } = DescriptionList;
const RadioGroup = Radio.Group;

import { syncPatentInfo, getFeeDetail } from '../../services/api';

import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './patent.less';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = {
  ALL: '全部',
  ACTIVE: '生效',
  INACTIVE: '失效',
};

const statusArr = [
  {
    id: 'ACTIVE',
    name: '全部',
  },
];

const PAGE_SIZE = 50;

@connect(({ patent, loading }) => {
  return {
    patent,
    loading: loading.models.patent,
  };
})
@Form.create()
export default class List extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    name: null,
    code: null,
    type: null,
    status: 1,
    description: null,
  };

  componentDidMount() {
    // this.init();
  }

  init() {
    const { dispatch } = this.props;
    dispatch({
      type: 'patent/queryList',
      payload: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
        keywords: null,
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      keywords: null,
      ...formValues,
      ...filters,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'patent/queryList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'patent/queryList',
      payload: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
        keywords: null,
      },
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if (!fieldsValue.keywords) {
        return false;
      }

      const values = {
        keywords: fieldsValue.keywords,
        pageNum: 1,
        pageSize: PAGE_SIZE,
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'patent/queryList',
        payload: values,
      });
    });
  };

  async handleSync(type) {
    const { selectedRows } = this.state;

    const patentNoList = selectedRows.map(item => item.patentNo);

    const params = { type, patentNoList };

    const hide = message.loading('同步中', 0);

    const response = await syncPatentInfo(params);

    setTimeout(hide, 1000);

    if (response.code === 200) {
      return message.success('同步成功');
    } else {
      message.error(response.message);
    }
  }

  renderAdvancedForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="申请号/申请人">
              {getFieldDecorator('keywords')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>

          <Col md={16} sm={24}>
            <span style={{ float: 'left', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>

        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={24} sm={24}>
            <span style={{ float: 'left', marginBottom: 24 }}>
              <Button type="primary" onClick={this.handleSync.bind(this, 0)}>
                同步状态
              </Button>
              <Button
                style={{ marginLeft: 8 }}
                type="primary"
                onClick={this.handleSync.bind(this, 1)}
              >
                同步费用
              </Button>
              <span style={{ marginLeft: 8, color: '#990000' }}>
                注：如需导出费用信息，需先同步费用信息，导出的缴费Excel表格可直接导入【电子申请网】进行缴费
              </span>
            </span>
          </Col>
          <Col md={8} sm={24} />
          <Col md={8} sm={24} />
        </Row>
      </Form>
    );
  }

  async handleGetFee(item) {
    const hide = message.loading('加载中', 0);

    const response = await getFeeDetail({
      patent: item.patentNo,
    });

    setTimeout(hide, 1000);

    if (response.code === 200) {
      this.setState({
        feeDetail: response.data,
        modalVisible: true,
      });
    } else {
      message.error(response.message);
    }
  }

  handleOnchange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  onChange(field, value, dateString) {
    this.setState({
      [field]: dateString,
    });
  }

  onRadioChange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  handleCancel = e => {
    this.setState({
      modalVisible: false,
    });
  };

  renderForm() {
    return this.renderAdvancedForm();
  }

  render() {
    let { patent: { data }, loading } = this.props;
    const { selectedRows, modalVisible } = this.state;

    const columns = [
      {
        title: '专利申请号',
        dataIndex: 'patentNo',
      },
      {
        title: '专利名称',
        dataIndex: 'patentTi',
      },
      {
        title: '申请人',
        dataIndex: 'patentPa',
      },
      {
        title: '申请日',
        dataIndex: 'patentAd',
      },
      {
        title: '法律状态',
        dataIndex: 'patentLsnt',
      },
      {
        title: '状态同步时间',
        dataIndex: 'a',
      },
      {
        title: '应缴费',
        dataIndex: 'b',
        render: (val, item) => (
          <span>
            <a href="javascript:;" onClick={this.handleGetFee.bind(this, item)}>
              {val}
            </a>
          </span>
        ),
      },
      {
        title: '缴费截止日',
        dataIndex: 'c',
      },
    ];

    return (
      <PageHeaderLayout title="专利检索">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>

        <Modal
          style={{ width: '800px' }}
          title="新增角色"
          visible={this.state.modalVisible}
          onOk={this.handleCancel.bind(this)}
          onCancel={this.handleCancel.bind(this)}
        >
          <DescriptionList size="large" title="" col="1" />
        </Modal>
      </PageHeaderLayout>
    );
  }
}
